// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
    data: {
        img: "",
        currentTimeStamp: 0,
        car: {},
        longitude: 113.324520,
        latitude: 23.099994,
        markers: [{
            latitude: 23.099994,
            longitude: 113.324520,
            width: 50,
            height: 50
        }],
        mmarkerssave: [{
            latitude: 23.099994,
            longitude: 113.324520,
            width: 50,
            height: 50
        }],
        polyline: [{ // 定义连线
            points: [],
            color: "#FF0000DD", // 连线颜色
            width: 2, // 连线宽度
            dottedLine: false // 是否虚线
        }],
        Date: "",
        num: [],
        device: "",
        name: [],
        everyName: "",
        ppp1: [],
        jhrname: "",
        jhrage: "",
        falseChange: "",

    },
    onLoad: function () {
        let currentTimeStamp = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0, 8)
        this.setData({
            currentTimeStamp: currentTimeStamp
        });
        // 导航栏
        // 1.获取屏幕可使用宽度
        let windowWidth = wx.getSystemInfoSync().windowWidth;
        // 2.获取状态栏高度
        const statusBarHeight = wx.getSystemInfoSync().statusBarHeight;
        //3.获取胶囊按钮位置信息
        const menuButton = wx.getMenuButtonBoundingClientRect();
        this.setData({
            navtop: menuButton.top
        })
    },
    onShow() {
        this.mapCtx = wx.createMapContext('map');
        const that = this
        const app = getApp()
        this.setData({
            num: [],
            name: [],
            falseChange: true
        })
        wx.request({
            url: 'https://dj.ifankui.com/api/usrEn/deviceList',
            method: "POST",
            data: {
                openid: app.globalData.openid
            },
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            success: (res) => {
                console.log(res);
                for (let i = 0; i < res.data.data.length; i++) {
                    this.data.num.push(res.data.data[i].device_code);
                    this.data.name.push(res.data.data[i].xm)
                }
                const newnum = this.data.num
                const newname = this.data.name
                this.setData({
                    num: newnum,
                    name: newname,
                })
                console.log(this.data.num);
                console.log(app.globalData);
            }
        })
        wx.request({
            url: 'https://dj.ifankui.com/api/usrEn/getProfile',
            method: 'POST',
            data: {
                openid: app.globalData.openid,
            },
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            success(res) {
                console.log(res);
                const birthDate = res.data.data.sfz.substring(6, 14)
                const year = parseInt(birthDate.substring(0, 4), 10);
                const month = parseInt(birthDate.substring(4, 6), 10);
                const day = parseInt(birthDate.substring(6, 8), 10);
                const today = new Date();
                let age = today.getFullYear() - year;
                that.setData({
                    img: res.data.data.headimg,
                    jhrname: res.data.data.realname,
                    jhrage: age
                })
            }
        })
    },
    getName(e) {
        console.log(e);
        this.setData({
            device: e.currentTarget.dataset.value
        })
        this.getDate()
    },
    bindDateChange(e) {
        console.log(e);
        this.setData({
            Date: e.detail.value
        }, () => {
            this.getDate()
            console.log(this.data.Date);
        })
    },
    bindDateChangelaoren(e) {
        console.log(this.data.num);
        console.log(this.data.name);
        const index = e.detail.value; // 获取选择的索引
        const selectedDevice = this.data.num[index]; // 获取设备代码
        const selecteName = this.data.name[index]
        this.setData({
            device: selectedDevice,
            everyName: selecteName,
        }, () => {
            if (this.data.Date.length != 0) {
                this.getDate(); // 调用获取数据的方法
                console.log('Selected device:', this.data.device);
            } else {
                console.log('尚未选择日期');
            }
        });
    },
    getDate() {
        console.log(this.data.falseChange);
        if (this.data.falseChange !== true) {
            wx.showToast({
                title: '请等待动画结束', // 提示的内容
                icon: 'none', // 图标，有效值：success, loading, none
                duration: 2000 // 提示的延迟时间，单位毫秒
            });
            return;
        } else {
            this.setData({
                falseChange: false
            })
        }

        const app = getApp()
        const that = this
        console.log(app.globalData.device_code);
        wx.request({
            url: 'https://dj.ifankui.com/api/device/getDeviceHistoryByDay',
            method: "POST",
            data: {
                openid: app.globalData.openid,
                device_code: this.data.device,
                day: this.data.Date
            },
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            success(res) {
                console.log(res);
                if (res.data.status == 'error') {
                    console.log("未选择老人")
                    that.setData({
                        falseChange: true
                    })
                    return;
                } else {
                    const markers1 = []
                    const polyline = []
                    let ppp = []
                    res.data.history.forEach(element => {
                        if (element.loc.length > 1) {
                            ppp.push(element)
                        }
                    });
                    that.setData({
                        ppp1: ppp
                    })
                    ppp.forEach((element, index) => {
                        console.log(index, res.data.history.length - 1);
                        var pp3 = ''
                        if (index == ppp.length - 1) {
                            pp3 = "终点:"

                        } else if (index == 0) {
                            pp3 = "起点:"
                        }
                        console.log(pp3);
                        if (element.loc.length > 1) {
                            const pp = element.loc.split(',')
                            const pp2 = element.dt.split(' ')

                            console.log(pp[0], pp[1]);
                            pp2[1] = pp2[1].slice(0, -3)
                            console.log(pp[1]);
                            const marker = {
                                id: index,
                                latitude: pp[1],
                                longitude: pp[0],
                                width: 20,
                                height: 20,
                                callout: {
                                    content: pp3 + pp2[1], // 标记内容
                                    color: '#000000',
                                    fontSize: 12,
                                    borderRadius: 5,
                                    bgColor: '#ffffff',
                                    padding: 2,
                                    display: 'BYCLICK' // 始终显示文字标签
                                }
                            }
                            const polyline1 = {
                                latitude: pp[1],
                                longitude: pp[0],
                            }
                            polyline.push(polyline1)
                            markers1.push(marker)
                        }
                    })
                    that.setData({
                        markers: markers1,
                        mmarkerssave: markers1,
                        'polyline[0].points': polyline
                    }, () => {
                        console.log(that.data.markers.length);
                        that.setData({
                            includePoints: that.data.markers.map(marker => ({
                                latitude: marker.latitude,
                                longitude: marker.longitude,
                            }))
                        });
                        if (that.data.markers.length >= 2) {
                            that.startAnimation();
                            console.log("动画开始");
                        } else {
                            console.log("只有一个位置");
                            return;
                        }


                    })
                }
            }
        })
    },
    startAnimation() {
        let timer
        let index = 0;
        const path = this.data.polyline[0].points;
        console.log(path);
        let progress = 0
        timer = setInterval(() => {
            let start = path[index];
            let end = path[index + 1];
            if (progress <= 1) {
                progress = progress + 0.02
            }
            let newLat = parseFloat(start.latitude) + (end.latitude - start.latitude) * progress;
            let newLng = parseFloat(start.longitude) + (end.longitude - start.longitude) * progress;
            // 更新标记位置
            this.setData({
                markers: [{
                    id: 1,
                    latitude: newLat,
                    longitude: newLng,
                    width: 15,
                    height: 15,
                    iconPath: '/images/blue2.png',

                }]
            });

            if (progress >= 0.95) {
                progress = 0
                index = index + 1
                console.log(index, path.length - 1);
                if (index == path.length - 1) {
                    clearInterval(timer);
                    this.setData({
                        falseChange: true
                    });
                    console.log(this.data.falseChange);
                    // 设置 falseChange 为 true
                    setTimeout(() => {
                        this.setData({
                            markers: []
                        }, () => {
                            this.setData({
                                markers: this.data.mmarkerssave
                            }, 1000);
                        });
                    }, 10); // 延迟 10 毫秒
                }
            }
            // console.log(this.data);
        }, 40) // 100ms更新一次

    },
})